package com.xuecheng.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xuecheng.base.exception.BusinessException;
import com.xuecheng.base.exception.CommonError;
import com.xuecheng.base.model.PageParams;
import com.xuecheng.base.model.PageResult;
import com.xuecheng.content.model.dto.AddCourseDto;
import com.xuecheng.content.model.dto.CourseBaseInfoDto;
import com.xuecheng.content.model.dto.EditCourseDto;
import com.xuecheng.content.model.dto.QueryCourseParamsDto;
import com.xuecheng.content.model.po.*;
import com.xuecheng.content.mapper.CourseBaseMapper;
import com.xuecheng.content.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

import static sun.invoke.util.ValueConversions.cast;

/**
 * <p>
 * 课程基本信息 服务实现类
 * </p>
 *
 * @author itcast
 */
@Slf4j
@Service
public class CourseBaseServiceImpl extends ServiceImpl<CourseBaseMapper, CourseBase> implements CourseBaseService {


    @Resource
    private CourseMarketService courseMarketService;

    @Resource
    private CourseCategoryService courseCategoryService;

    @Resource
    private TeachplanService teachplanService;

    @Resource
    private CourseTeacherService courseTeacherService;

    @Resource
    private TeachplanMediaService teachplanMediaService;

    /**
     * 审核状态：未提交
     */
    private static final String NO_SUBMIT = "202002";
    /**
     * 未通过
     */
    private static final String NO_PASS = "202001";

    /**
     * 课程信息分页查询
     * @param pageParams
     * @param queryCourseParams
     * @return
     */
    @Override
    public PageResult<CourseBase> queryCourseBasePageList(PageParams pageParams, QueryCourseParamsDto queryCourseParams) {
        //课程名称
        String courseName = queryCourseParams.getCourseName();
        //审核状态
        String auditStatus = queryCourseParams.getAuditStatus();
        //课程状态
        String publishStatus = queryCourseParams.getPublishStatus();
        //构建条件构造器
        LambdaQueryWrapper<CourseBase> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(courseName),CourseBase::getName,courseName)
                .eq(StringUtils.isNotBlank(auditStatus),CourseBase::getAuditStatus,auditStatus)
                .eq(StringUtils.isNotBlank(publishStatus),CourseBase::getStatus,publishStatus);
        //构建分页对象
        Page<CourseBase> courseBasePage = new Page<>(pageParams.getPageNo(), pageParams.getPageSize());
        //分页查询
        page(courseBasePage,queryWrapper);
        return new PageResult<CourseBase>(courseBasePage.getRecords(),courseBasePage.getTotal(),courseBasePage.getCurrent(),courseBasePage.getSize());
    }

    /**
     * 添加课程
     * @param companyId
     * @param addCourseDto
     * @return
     */
    @Transactional
    @Override
    public CourseBaseInfoDto addCourse(Long companyId,AddCourseDto addCourseDto) {
        //==============================向课程基本信息添加记录==============================
        CourseBase courseBase = new CourseBase();
        BeanUtils.copyProperties(addCourseDto,courseBase);
        courseBase.setCompanyId(companyId);
        courseBase.setCreateDate(LocalDateTime.now());
        //课程默认为未审核状态
        courseBase.setAuditStatus("202002");
        //课程默认为未发布
        courseBase.setStatus("203001");
        boolean courseBaseRes = save(courseBase);
        if (!courseBaseRes) throw new BusinessException("操作失败");
        //==============================向课程营销表中添加记录==============================
        CourseMarket courseMarket = new CourseMarket();
        //设置课程id
        courseMarket.setId(courseBase.getId());
        BeanUtils.copyProperties(addCourseDto,courseMarket);
        boolean res = saveCourseMarket(courseMarket);
        if (!res) throw new BusinessException("操作失败");
        //构建课程信息传输对象
        return getCourseBaseInfoDto(courseBase,courseMarket);
    }

    /**
     * 根据id获取课程信息
     * @param id
     * @return
     */
    @Override
    public CourseBaseInfoDto getCourseBaseInfoById(Long id) {
        //课程基本信息
        CourseBase courseBase = getById(id);
        if (courseBase==null) BusinessException.cast(CommonError.QUERY_NULL);
        //课程营销信息
        CourseMarket courseMarket = courseMarketService.getById(id);
        return getCourseBaseInfoDto(courseBase,courseMarket);
    }

    /**
     * 修改课程信息
     * @param companyId
     * @param editCourseDto
     * @return
     */
    @Override
    @Transactional
    public CourseBaseInfoDto updateCourseBaseInfo(Long companyId,EditCourseDto editCourseDto) {
        if (editCourseDto == null) {
            BusinessException.cast(CommonError.REQUEST_NULL);
        }
        //获取课程id
        Long courseId = editCourseDto.getId();
        if (courseId == null || courseId <= 0) {
            BusinessException.cast(CommonError.PARAMS_ERROR);
        }
        //查询课程是否存在
        CourseBase courseBaseInfo = getById(courseId);
        if (courseBaseInfo == null) {
            throw new BusinessException("课程不存在");
        }
        //本机构只能修改本机构的课程
        if (!companyId.equals(courseBaseInfo.getCompanyId())){
            throw new BusinessException("无权限修改课程信息");
        }
        //修改课程基本信息
        CourseBase courseBase = new CourseBase();
        BeanUtils.copyProperties(editCourseDto,courseBase);
        boolean baseRes = updateById(courseBase);
        //修改课程营销信息
        CourseMarket courseMarket = new CourseMarket();
        BeanUtils.copyProperties(editCourseDto,courseMarket);
        boolean marketRes = courseMarketService.updateById(courseMarket);
        if (!(baseRes&&marketRes)) {
            BusinessException.cast(CommonError.UNKOWN_ERROR);
        }
        CourseBaseInfoDto courseBaseInfoDto = new CourseBaseInfoDto();
        BeanUtils.copyProperties(editCourseDto,courseBaseInfoDto);
        return courseBaseInfoDto;
    }

    /**
     * 删除课程信息
     * @param courseId
     */
    @Transactional
    @Override
    // TODO 只能删除机构自己的课
    public void deleteCourseInfo(long courseId) {
        if (courseId <= 0) {
            BusinessException.cast(CommonError.PARAMS_ERROR);
        }
        //查询课程信息是否存在
        CourseBase courseBase = getById(courseId);
        if (courseBase==null) BusinessException.cast(CommonError.QUERY_NULL);
        //课程状态为未提交才可以删除
        if (!courseBase.getAuditStatus().equals(NO_SUBMIT)){
            throw new BusinessException("无法删除！");
        }
        //删除课程基本信息
        boolean res1 = removeById(courseId);
        if (!res1) throw new BusinessException("课程基本信息删除失败!");

        //删除营销信息
        boolean res2 = courseMarketService.removeById(courseId);
        if (!res2) throw new BusinessException("课程营销信息删除失败!");

        //删除课程章节信息
        LambdaQueryWrapper<Teachplan> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Teachplan::getCourseId,courseId);
        boolean res3 = teachplanService.remove(queryWrapper);
        if (!res3) throw new BusinessException("课程学习计划删除失败!");

        //删除课程的所有媒体资源信息
        LambdaQueryWrapper<TeachplanMedia> teachplanMediaLambdaQueryWrapper = new LambdaQueryWrapper<>();
        teachplanMediaLambdaQueryWrapper.eq(TeachplanMedia::getCourseId,courseId);
        int count = teachplanMediaService.count(teachplanMediaLambdaQueryWrapper);
        if (count > 0) {
            boolean res4 = teachplanMediaService.remove(teachplanMediaLambdaQueryWrapper);
            if (!res4) throw new BusinessException("课程媒体资源删除失败!");
        }
        //删除课程教师信息
        LambdaQueryWrapper<CourseTeacher> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(CourseTeacher::getCourseId,courseId);
        int count1 = courseTeacherService.count(queryWrapper1);
        if (count1 > 0) {
            boolean res5 = courseTeacherService.remove(queryWrapper1);
            if (!res5) throw new BusinessException("课程老师信息删除失败!");
        }
    }

    /**
     * 保存课程营销信息
     * @param courseMarket
     * @return
     */
    private boolean saveCourseMarket(CourseMarket courseMarket){
        //参数校验
        String charge = courseMarket.getCharge();
        if (StringUtils.isBlank(charge)) {
            throw new BusinessException("收费规则不能为空");
        }
        //如果课程为收费
        if (charge.equals("201001")){
            Float price = courseMarket.getPrice();
            if (price == null || price <= 0) {
                throw new BusinessException("price参数有误");
            }
        }
        CourseMarket byId = courseMarketService.getById(courseMarket.getId());
        boolean res = false;
        if (byId == null) {
            //说明没有课程营销信息
            res = courseMarketService.save(courseMarket);
        }else {
            res = courseMarketService.updateById(courseMarket);
        }
        return res;
    }

    /**
     * 获得课程信息传输对象
     * @param courseBase
     * @param courseMarket
     * @return
     */
    private CourseBaseInfoDto getCourseBaseInfoDto(CourseBase courseBase,CourseMarket courseMarket){
        if (courseBase == null) {
            return null;
        }
        CourseBaseInfoDto courseBaseInfoDto = new CourseBaseInfoDto();
        BeanUtils.copyProperties(courseBase,courseBaseInfoDto);
        // todo dev阶段使测试数据不报错
        if (courseMarket!=null) {
            BeanUtils.copyProperties(courseMarket, courseBaseInfoDto);
        }
        //设置大分类小分类名称
        courseBaseInfoDto.setStName(courseCategoryService.getById(courseBaseInfoDto.getSt()).getName());
        courseBaseInfoDto.setMtName(courseCategoryService.getById(courseBaseInfoDto.getMt()).getName());
        return courseBaseInfoDto;
    }
}
